#include "stm32_engine.h"

void stm32_engine_init(){
	TIM_TimeBaseInitTypeDef tim_base_init_struct;
	TIM_OCInitTypeDef tim_oc_init_struct;
	GPIO_InitTypeDef gpio_init_struct;

	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

	gpio_init_struct.GPIO_Pin = GPIO_Pin_6|GPIO_Pin_7;
	gpio_init_struct.GPIO_Mode = GPIO_Mode_AF_PP;
	gpio_init_struct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&gpio_init_struct);

	gpio_init_struct.GPIO_Pin = GPIO_Pin_0|GPIO_Pin_1;
	gpio_init_struct.GPIO_Mode = GPIO_Mode_AF_PP;
	gpio_init_struct.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB,&gpio_init_struct);

	tim_base_init_struct.TIM_Period = 200;
	tim_base_init_struct.TIM_Prescaler = 35;
	tim_base_init_struct.TIM_ClockDivision = TIM_CKD_DIV1;
	tim_base_init_struct.TIM_CounterMode = TIM_CounterMode_Up;
	TIM_TimeBaseInit(TIM3,&tim_base_init_struct);

	tim_oc_init_struct.TIM_OCMode = TIM_OCMode_PWM1;
	tim_oc_init_struct.TIM_OutputState = TIM_OutputState_Enable;
	tim_oc_init_struct.TIM_Pulse = 0;
	tim_oc_init_struct.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM_OC1Init(TIM3, &tim_oc_init_struct);

	tim_oc_init_struct.TIM_OCMode = TIM_OCMode_PWM1;
	tim_oc_init_struct.TIM_OutputState = TIM_OutputState_Enable;
	tim_oc_init_struct.TIM_Pulse = 0;
	tim_oc_init_struct.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM_OC2Init(TIM3, &tim_oc_init_struct);


	tim_oc_init_struct.TIM_OCMode = TIM_OCMode_PWM1;
	tim_oc_init_struct.TIM_OutputState = TIM_OutputState_Enable;
	tim_oc_init_struct.TIM_Pulse = 0;
	tim_oc_init_struct.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM_OC3Init(TIM3, &tim_oc_init_struct);

	tim_oc_init_struct.TIM_OCMode = TIM_OCMode_PWM1;
	tim_oc_init_struct.TIM_OutputState = TIM_OutputState_Enable;
	tim_oc_init_struct.TIM_Pulse = 0;
	tim_oc_init_struct.TIM_OCPolarity = TIM_OCPolarity_High;
	TIM_OC4Init(TIM3, &tim_oc_init_struct);

	TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
	TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
	TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
	TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);
	TIM_ARRPreloadConfig(TIM3, ENABLE);
	TIM_Cmd(TIM3, ENABLE);
}


void stm32_engine_set_power(float fpower){
	uint16_t power = fpower*100+100;
	TIM3->CCR2 = power;
	TIM3->CCR3 = power;
}

void stm32_engine_set_cnv(float cnvf,uint8_t ch){
	uint16_t cnv = cnvf*200;
	switch(ch){
		case 0:
			TIM3->CCR1 = cnv;	
		break;
		case 1:
			TIM3->CCR2 = cnv;
		break;
		case 2:
			TIM3->CCR3 = cnv;
		break;
		case 3:
			TIM3->CCR4 = cnv;
		break;
	}
}
